import { useEffect, useState } from 'react';
import { Link, useRequest, history } from 'umi';
import { useLocalStorageState } from 'ahooks';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { TableDropdown } from '@ant-design/pro-table';

import {
  Table,
  Space,
  Card,
  Button,
  Form,
  Input,
  Select,
  PageHeader,
  Modal,
  Row,
  Col,
  Descriptions,
  Breadcrumb,
  TreeSelect,
  Image,
  Empty,
  Divider,
} from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import zhCN from 'antd/lib/locale/zh_CN';
import moment from 'moment';

const { Option } = Select;

const CreateBoard = () => {
  const [opt, setOpt] = useState({}); //保存form cond 中的option
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);

  //根据boardId获取单个画板数据
  const getOneBoardData = useRequest(
    (boardId) => {
      return {
        url: `http://10.1.40.84:9993/getOneBoardData?boardId=${boardId}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      onSuccess: (result, params) => {
        console.log();
        const { theme, boardColumnMap, boardCondMap } = result;
        let boardColumnMapTemp: any = [];
        boardColumnMap.map((item: any) => {
          boardColumnMapTemp.push(item.key);
        });
        getTableByTheme.run(theme).then((TableName: any) => {
          // console.log(JSON.parse(TableName))

          //后端还缺一个表名
          getColAndCondByTbl.run(result.tableCha).then(() => {
            form.setFieldsValue({
              theme: theme,
              tableName: result.tableCha,
              column: boardColumnMapTemp,
              cond: boardCondMap,
            });
            form.submit();
          });
        });
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
      // refreshDeps: [boardId],
    },
  );
  //判断是“新建”还是“编辑”
  useEffect(() => {
    const boardIdTemp = history.location.pathname.replace(
      '/DataBoard/CreateBoard/',
      '',
    );
    if (boardIdTemp !== 'new') {
      getOneBoardData.run(boardIdTemp);
    }
  }, []);

  //根据主题获取表名
  const getTableByTheme = useRequest(
    (theme) => {
      return {
        url: `http://10.1.40.84:9993/getTableByTheme?theme=${theme}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      onSuccess: (result, params) => {
        // console.log(JSON.parse(result));
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // refreshDeps: [theme],
      manual: true,
    },
  );
  //根据表名获取“列”和“条件”
  const getColAndCondByTbl = useRequest(
    (tableName) => {
      return {
        url: `http://10.1.40.84:9993/getColAndCondByTbl?tableName=${tableName}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      onSuccess: (result, params) => {
        // console.log(JSON.parse(result));
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // refreshDeps: [tableName],
      manual: true,
    },
  );
  //临时预览看板
  const getTempBoardData = useRequest(
    (data) => {
      return {
        url: `http://10.1.40.84:9993/getTempBoardData`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        // console.log(JSON.parse(result));
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
      formatResult: (res) => {
        if (res?.data) {
          let columnsTemp: any = [];
          res.data.columns.map((item: any) => {
            if (
              item.key === 'PAPER_TITLE' ||
              item.key === 'AUTHOR' ||
              item.key === 'PERIODICAL_NAME' ||
              item.key === 'ISSUE_NUM' ||
              item.key === 'PATENT_NAME' ||
              item.key === 'GRANT_NUM' ||
              item.key === 'CONTRACT_NAME' ||
              item.key === 'ACHIEVE_NAME' ||
              item.key === 'PATENT_NUM' ||
              item.key === 'TRANS_COMPANY' ||
              item.key === 'TRANS_COMPANY' ||
              item.key === 'COMPANY_NAME' ||
              item.key === 'ENTERPRISE_NAME' ||
              item.key === 'TOPIC' ||
              item.key === 'NAME' ||
              item.key === 'BOOK_NAME' ||
              item.key === 'MEETING_NAME' ||
              item.key === 'PROJECT_NAME' ||
              item.key === 'PROJECT_SOURCE'
            ) {
              columnsTemp.push({
                ...item,
                ellipsis: true,
              });
            } else if (item.key === 'PIC_PATH') {
              columnsTemp.push({
                ...item,
                render: (text: String) => {
                  if (text.includes('http')) {
                    return <Image src={text} />;
                  } else {
                    return <div>{text}</div>;
                  }
                },
              });
            } else {
              columnsTemp.push(item);
            }
          });
          return {
            data: res.data.data,
            columns: columnsTemp,
          };
        }
        return undefined;
        // return
      },
    },
  );
  //保存看板
  const addBoard = useRequest(
    (data) => {
      return {
        url: `http://10.1.40.84:9993/addBoard`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        // console.log(JSON.parse(result));
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
    },
  );
  //根据form cond第一个框确定第二个框和第四个隐藏框的数值
  const firstOnchange = (value: any, fieldsKey: any) => {
    console.log(opt);
    console.log(getColAndCondByTbl.data);

    let optTemp: any = JSON.parse(JSON.stringify(opt));
    // let optTemp: any = opt;

    // let objTemp: any = JSON.parse(getColAndCondByTbl.data).cond.filter(
    //   (item: any) => {
    //     return item.ID === value;
    //   },
    // );
    let objTemp: any = getColAndCondByTbl.data.cond.filter((item: any) => {
      return item.ID === value;
    });
    optTemp[fieldsKey] = objTemp[0].OPT;
    let condTemp: any = form.getFieldValue('cond');
    console.log(condTemp);
    condTemp[fieldsKey].datatype = objTemp[0].DATATYPE;

    form.setFieldsValue({
      cond: condTemp,
    });

    setOpt(optTemp);
  };
  //将formdata适配成后端要的参数
  const paramAdaptor = (formData: any) => {
    let columnTemp: any = [];
    if (formData.column) {
      formData.column.map((item: any) => {
        getColAndCondByTbl.data.column.map((itemsub: any) => {
          if (item === itemsub.key) {
            columnTemp.push(itemsub);
          }
        });
      });
    }
    formData.column = columnTemp;
    if (!formData.cond) {
      formData.cond = [];
    }
    return formData;
  };
  //一套保存modal  填写看板名称
  const showModal = () => {
    setIsModalVisible(true);
  };
  const handleOk = () => {
    form
      .validateFields()
      .then((item) => {
        addBoard.run(paramAdaptor(item)).then(() => {
          history.push('/DataExport/DataBoard');
        });
      })
      .catch((err) => {
        console.log(err);
      });
    setIsModalVisible(false);
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const onFinish = (value: any) => {
    getTempBoardData.run(paramAdaptor(value));
  };
  //调整Table的srcoll属性
  const TableScroll = (theme: any, columnsNum: any) => {
    switch (theme) {
      case '社会服务':
        return {
          x: 800,
        };
      case '人才培养':
      case '合作交流':
        return false;
      default:
        return {
          x: 1000,
        };
    }
  };
  return (
    <PageContainer
      header={{
        title: '新建数据看板',
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>数据导出</Breadcrumb.Item>
            <Breadcrumb.Item>数据看板</Breadcrumb.Item>
            <Breadcrumb.Item>新建数据看板</Breadcrumb.Item>
          </Breadcrumb>
        ),
      }}
    >
      {/* <Button onClick={() => {
        console.log(getTempBoardData?.data);
      }}>CESHI</Button> */}
      <div style={{ background: 'white', width: '100%' }}>
        <Form form={form} onFinish={onFinish} layout="horizontal">
          <Row gutter={6} style={{ padding: 10 }}>
            <Col span={9}>
              <Card type="inner" title="1、选择数据">
                <Form.Item
                  name="uselessField"
                  initialValue={'1'}
                  rules={[{ required: true, message: '请输入名称' }]}
                >
                  <Select style={{ width: '100%' }}>
                    <Option value="1">
                      河北工业大学电工装备可靠性与智能化省部共建国家重点实验室
                    </Option>
                  </Select>
                </Form.Item>
                <Form.Item
                  name="theme"
                  // initialValue={'论文'}
                  rules={[{ required: true, message: '请输入主题' }]}
                >
                  <Select
                    style={{ width: '100%' }}
                    onChange={(value: any) => {
                      getTableByTheme.run(value).then(() => {
                        form.setFieldsValue({ tableName: undefined });
                      });
                      // setTheme(value);
                    }}
                  >
                    <Option value="论文">论文</Option>
                    <Option value="专利">专利</Option>
                    <Option value="项目">项目</Option>
                    <Option value="成果">成果</Option>
                    <Option value="著作">著作</Option>
                    <Option value="实验平台">实验平台</Option>
                    <Option value="合作交流">合作交流</Option>
                    <Option value="社会服务">社会服务</Option>
                    <Option value="人才培养">人才培养</Option>
                  </Select>
                </Form.Item>
                <Form.Item
                  name="tableName"
                  // initialValue={'PAPER'}
                  rules={[{ required: true, message: '请输入表名' }]}
                >
                  <Select
                    style={{ width: '100%' }}
                    onChange={(value: any) => {
                      getColAndCondByTbl.run(value);
                      form.setFieldsValue({
                        column: undefined,
                        cond: undefined,
                      });
                    }}
                  >
                    {getTableByTheme.data
                      ? getTableByTheme.data.map((item: any) => {
                          return (
                            <Option value={item.ID} key={item.ID}>
                              {item.NAME}
                            </Option>
                          );
                        })
                      : null}
                  </Select>
                </Form.Item>
              </Card>
              <Card type="inner" title="2、选择指标">
                <Form.Item
                  name="column"
                  rules={[{ required: true, message: '请输入指标' }]}
                >
                  <Select
                    style={{ width: '100%' }}
                    mode="multiple"
                    allowClear
                    dropdownRender={(menu) => (
                      <>
                        {menu}
                        <Divider style={{ margin: '8px 0' }} />
                        <Space align="center" style={{ padding: '0 8px 4px' }}>
                          <Button
                            type="link"
                            size="small"
                            onClick={() => {
                              let columnTemp: any = [];
                              if (getColAndCondByTbl.data.column) {
                                getColAndCondByTbl.data.column.map(
                                  (item: any) => {
                                    columnTemp.push(item.key);
                                  },
                                );
                              }
                              form.setFieldsValue({ column: columnTemp });
                            }}
                          >
                            全选
                          </Button>
                        </Space>
                      </>
                    )}
                  >
                    {getColAndCondByTbl.data
                      ? getColAndCondByTbl.data.column.map((element: any) => {
                          return (
                            <Option value={element.key} key={element.key}>
                              {element.title}
                            </Option>
                          );
                        })
                      : null}
                  </Select>
                </Form.Item>
              </Card>
              <Card type="inner" title="3、选择条件">
                <Form.List name="cond">
                  {(fields, { add, remove }) => (
                    <>
                      {fields.map(({ key, name, ...restField }) => (
                        <Space
                          key={key}
                          style={{ display: 'flex', marginBottom: 8 }}
                          align="baseline"
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'id']}
                            rules={[{ required: true, message: '请输入id' }]}
                          >
                            <Select
                              style={{ width: 120 }}
                              onChange={(value: any) => {
                                firstOnchange(value, key);
                              }}
                            >
                              {getColAndCondByTbl.data
                                ? getColAndCondByTbl.data.cond.map(
                                    (element: any) => {
                                      return (
                                        <Option
                                          value={element.ID}
                                          key={element.ID}
                                        >
                                          {element.NAME}
                                        </Option>
                                      );
                                    },
                                  )
                                : null}
                            </Select>
                          </Form.Item>
                          <Form.Item
                            {...restField}
                            name={[name, 'opt']}
                            rules={[{ required: true, message: '请输入opt' }]}
                          >
                            <Select style={{ width: 100 }}>
                              {opt[key]
                                ? opt[key].map((element: any) => {
                                    return (
                                      <Option value={element} key={element}>
                                        {element}
                                      </Option>
                                    );
                                  })
                                : null}
                            </Select>
                          </Form.Item>
                          <Form.Item
                            {...restField}
                            name={[name, 'value']}
                            rules={[{ required: true, message: '请输入value' }]}
                          >
                            <Input placeholder="数值" />
                          </Form.Item>
                          <Form.Item
                            {...restField}
                            name={[name, 'datatype']}
                            rules={[{ required: true, message: '请输入value' }]}
                            hidden
                            // initialValue={dataType[key] ? dataType[key] : "666"}
                          >
                            <Input placeholder="数值" />
                          </Form.Item>
                          <MinusCircleOutlined onClick={() => remove(name)} />
                        </Space>
                      ))}
                      <Form.Item>
                        <Button
                          type="dashed"
                          onClick={() => add()}
                          block
                          icon={<PlusOutlined />}
                        >
                          添加条件
                        </Button>
                      </Form.Item>
                    </>
                  )}
                </Form.List>
              </Card>
            </Col>
            <Col span={15}>
              {getTempBoardData?.data ? (
                <ProTable
                  headerTitle="预览"
                  cardProps={{ bordered: true }}
                  size="small"
                  bordered
                  scroll={TableScroll(
                    form.getFieldValue('theme'),
                    getTempBoardData.data?.columns?.length,
                  )}
                  rowKey={() => Math.random()}
                  dataSource={getTempBoardData.data.data}
                  columns={getTempBoardData.data.columns}
                  search={false}
                  pagination={{
                    hideOnSinglePage: true,
                  }}
                  options={{
                    fullScreen: true,
                    reload: false,
                    setting: false,
                    density: false,
                  }}
                  toolBarRender={() => [
                    <Button
                      type="primary"
                      size="small"
                      onClick={() => {
                        form.submit();
                      }}
                    >
                      查询
                    </Button>,
                    <Button type="primary" size="small" onClick={showModal}>
                      保存
                    </Button>,
                    <Button type="primary" size="small">
                      <Link to="/DataExport/DataBoard">退出</Link>
                    </Button>,
                  ]}
                />
              ) : (
                <Card
                  title={'预览'}
                  type="inner"
                  extra={
                    <Space>
                      <Button
                        type="primary"
                        size="small"
                        onClick={() => {
                          form.submit();
                        }}
                      >
                        查询
                      </Button>
                      <Button type="primary" size="small" onClick={showModal}>
                        保存
                      </Button>
                      <Button type="primary" size="small">
                        <Link to="/DataExport/DataBoard">退出</Link>
                      </Button>
                    </Space>
                  }
                  style={{ padding: 0 }}
                >
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                </Card>
              )}
            </Col>
          </Row>

          <Modal
            title="保存看板"
            visible={isModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
            okText={'保存'}
            cancelText={'取消'}
          >
            <Form.Item
              label="看板名称"
              name="boardName"
              rules={[{ required: true }]}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 14 }}
            >
              <Input allowClear />
            </Form.Item>
          </Modal>
        </Form>
      </div>
    </PageContainer>
  );
};

export default CreateBoard;
